/** axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from 'axios'

axios.defaults.baseURL = ''
// 请求超时时间
axios.defaults.timeout = 120000
// post请求头
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.headers.get['Content-Type'] = 'application/json'
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*'
axios.defaults.headers.get['Access-Control-Allow-Origin'] = '*'

// 统一设置 put 请求头
axios.defaults.headers.put['Content-Type'] = 'application/json'

// 请求拦截器
axios.interceptors.request.use(
    config => {
        const token = localStorage.getItem('token') === 'login-success!'
        const loginTime = localStorage.getItem('loginTime')

        if (token) {
            // 检查token是否过期（2小时）
            if (loginTime && Date.now() - parseInt(loginTime) > 2 * 60 * 60 * 1000) {
                localStorage.removeItem('token')
                localStorage.removeItem('loginTime')
                window.location.href = '/#/login'
                return Promise.reject('登录已过期，请重新登录')
            }
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    error => Promise.error(error)
)

// 响应拦截器
axios.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return Promise.resolve(response)
        }
        return Promise.reject(response)
    },
    // 服务器状态码不是200的情况
    err => {
        if (err.toString() === 'Cancel') return new Promise(() => {
        })
        if (err && err.response) {
            switch (err.response.status) {
                case 302:
                    err.message = '重定向'
                    break
                case 400:
                    err.message = '请求错误'
                    break

                case 401:
                    err.message = '未授权，请登录'
                    break

                case 403:
                    err.message = '拒绝访问'
                    break

                case 404:
                    err.message = `请求地址出错: ${err.response.config.url}`
                    break
                case 408:
                    err.message = '请求超时'
                    break

                case 500:
                    err.message = '服务器出错，请稍后再试'
                    break

                case 501:
                    err.message = '网络未实现，请稍后再试'
                    break

                case 502:
                    err.message = '网络错误，请稍后再试'
                    break

                case 503:
                    err.message = '服务器不可用，请稍后再试'
                    break

                case 504:
                    err.message = '服务超时，请稍后再试'
                    break

                case 505:
                    err.message = 'HTTP版本不受支持'
                    break
                default:
                    err.message = '请求失败，请稍后再试'
            }
            console.log(err.message) // 屏蔽弹窗敏感信息，输出到控制台
        }
        return Promise.reject(err.response)
    }
)

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params, headerType) {
    let type = {}

    if (typeof headerType !== 'undefined') {
        type = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }
    }
    return new Promise((resolve, reject) => {
        axios
            .get(
                url,
                {
                    params: params,
                    headers: type.headers || {}
                },
                type
            )
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err && err.data)
            })
    })
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params, options = {}) {
    const opts = {...options, timeout: options.timeout}
    return new Promise((resolve, reject) => {
        axios
            .post(url, params instanceof FormData ? params : JSON.stringify(params), opts)
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err && err.data)
            })
    })
}

export function patch(url, params, isObject) {
    const newParams = isObject ? params : JSON.stringify(params)
    const type = isObject ? 'application/json' : 'application/x-www-form-urlencoded'
    return new Promise((resolve, reject) => {
        axios
            .patch(url, newParams, {
                headers: {
                    'Content-Type': type
                }
            })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err && err.data)
            })
    })
}

/**
 * put方法，对应put请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function put(url, params) {
    return new Promise((resolve, reject) => {
        axios
            .put(url, JSON.stringify(params))
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err && err.data)
            })
    })
}

export function deleteMethod(url, params) {
    return new Promise((resolve, reject) => {
        axios
            .delete(
                url,
                {
                    params
                },
                {
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                }
            )
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err && err.data)
            })
    })
}

export const $axios = axios
